//
//  HtmlViewController.m
//  OC和Html交互解决方案
//
//  Created by SmartStrategy on 2019/5/29.
//  Copyright © 2019 SmartStrategy. All rights reserved.
//

#import "HtmlViewController.h"
#import <WebKit/WebKit.h>

@interface HtmlViewController ()<WKNavigationDelegate, WKScriptMessageHandler,WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation HtmlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    NSString *weburl = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:weburl]]];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(250, 200, 100, 50);
    [button setTitle:@"原生调用H5" forState:(UIControlStateNormal)];
    button.backgroundColor = UIColor.greenColor;
    [button addTarget:self action:@selector(onClickH5) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button];
    
    UIButton *button1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button1.frame = CGRectMake(250, 200, 100, 50);
    [button1 setTitle:@"原生调用H5传参数" forState:(UIControlStateNormal)];
    button1.backgroundColor = UIColor.greenColor;
    [button1 addTarget:self action:@selector(onClickH5) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button1];
    
}

- (void)onClickH5{
    NSString *returnJSStr = [NSString stringWithFormat:@"refreshPage('11111')"];
    [self.webView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        NSLog(@"%@,%@", result, error);
    }];
}

- (void)onClickH51{
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 显示两个按钮，通过completionHandler回调判断用户点击的确定还是取消按钮
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(YES);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(NO);
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

// 显示一个带有输入框和一个确定按钮的，通过completionHandler回调用户输入的内容
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(alertController.textFields.lastObject.text);
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - WKScriptMessageHandler协议方法

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
    if ([message.name isEqualToString:@"changeOrientation"]) {
        NSInteger body = [message.body integerValue];
        [self changeOrientation:body];
    }
    else if ([message.name isEqualToString:@"selectBrowse"]) {
        [self selectBrowse];
    }
    else if ([message.name isEqualToString:@"saveFloorId"]) {
        [self saveFloorId:message.body];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSString *returnJSStr = [NSString stringWithFormat:@"refreshPage('11111')"];
    [self.webView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        NSLog(@"%@,%@", result, error);
    }];
}

#pragma mark - methods.

- (void)changeOrientation:(NSInteger)param {
    NSLog(@"changeOrientation---%ld", (long)param);
}

- (void)selectBrowse {
    NSLog(@"selectBrowse---");
}

- (void)saveFloorId:(NSString *)floorId {
    NSLog(@"saveFloorId---%@", floorId);
}

#pragma mark - lazy load.

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.javaScriptEnabled = YES;
        
        config.userContentController = [[WKUserContentController alloc] init];
        [config.userContentController addScriptMessageHandler:self name:@"changeOrientation"];
        [config.userContentController addScriptMessageHandler:self name:@"selectBrowse"];
        [config.userContentController addScriptMessageHandler:self name:@"saveFloorId"];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preferences;
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
        _webView.backgroundColor = UIColor.whiteColor;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    return _webView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
